//声明发送消息的XMLHttpRequest对象
var sendReq = createAjaxObj();
//声明发送检索消息的XMLHttpRequest对象
var receiveReq = createAjaxObj();
//设置上次取回的Message_ID
var lastMessage = 0;
//声明setTimeout()的返回值
var mTimer;
//聊天室的ID
var chatId;
//用户的id
var userId;
//startChat()方法:初始化全局变量后,每两秒钟向DB中发送一次请求
function startChat(){
    //将焦点设置到消输入框中
    document.getElementById('txt_message').focus();
    //调用initial()方法初始化chatId和userId变量
    initial();
    //调用getChatText()方法获得消息
    getChatText();
}
function initial(){
    chatId = document.frmmain.cid.value;
    userId = document.frmmain.uid.value;
}
//createAjaxObj()方法创建XMLHttpRequest对象
function createAjaxObj(){
    var httprequest = false;
    if(window.XMLHttpRequest)
    {
        //如果是Mozilla,Safari等浏览器
        httprequest=new XMLHttpRequest()
        if(httprequest.overrideMimeType)
            httprequest.overrideMimeType('text/xml')
    }else if(window.ActiverXObject)
    {
        //如果是IE浏览器
        try{
            httprequest=new ActiverXObject("Msxml2.XMLHTTP");        
        }catch(e){
            try{
                httprequest=new ActiverXObject("Microsoft.XMLHTTP");
            }catch(e){
            }
        }    
    }
    return httprequest;
}
//getChatText()向DB中发送请求,并获得最新的消息
function getChatText(){
    //判断上次请求的状态是否完成或者是还未发送请求
    //alert("sdfsdfsdf");
    if(receiveReq.readyState==4||receiveReq.readyState==0){
        //发送获得消息的服务器地址
        var submitURL = "getMessage?chatId="+chatId+"&last="+lastMessage;
        //建立请求
        receiveReq.open("GET",submitURL,true);
        //当请求状态改变时调用handleReceiveChat
        receiveReq.onreadystatechange=handleReceiveChat;
        //发送请求
        receiveReq.send(null);
    }
}
//新请求的状态改变时调用
function handleReceiveChat(){
    //此时请求已经完成
    if(receiveReq.readyState==4){
        //获得显示消息的图层元素对象
        var chat_div=document.getElementById("div_chat");
        //获得返回后的XML文件
        var xmldoc = receiveReq.responseXML;    
        
        //得到所有的新消息记录
        var message_nodes = xmldoc.getElementsByTagName("message");
        var n_messages = message_nodes.length;
        //alert(n_messages);
        //循环每一条新消息,组织成HTML格式数据
        for(var i=0;i<n_messages;i++){
            var user_node = message_nodes[i].getElementsByTagName("user");
            var text_node = message_nodes[i].getElementsByTagName("text");
            var time_node = message_nodes[i].getElementsByTagName("time");
            //alert(time_node[0].firstChild.nodeValue);
            chat_div.innerHTML+='(<font class="chatUser">'+user_node[0].firstChild.nodeValue+'</font>)&nbsp;said at &nbsp;';
            chat_div.innerHTML+='<font class="chatTime">'+time_node[0].firstChild.nodeValue+'</font><br />';
            chat_div.innerHTML+='<span class="title">'+text_node[0].firstChild.nodeValue+'</span><br />';
            chat_div.scrollTop = chat_div.scrollHeight;
            //每循环一条消息,记录到全局变量lastMessage中
            lastMessage = (message_nodes[i].getAttribute('id'));
        }
        //获取数据后,设置2秒钟后再次调用getChatText()方法
        mTimer = setTimeout('getChatText();',2000);
    }
}    
//sendChatText()方法向DB中添加消息记录
function sendChatText(){
    //如果输入的消息为空,提示用户输入
    if(document.getElementById('txt_message').value==''){
        alert("You have not entered a message");
        return;
    }
    //判断上次发送消息请求的状态是否完成或是还未发送请求
    if(sendReq.readyState == 4||sendReq.readyState == 0){
        //保存消息的服务器地址
        var submitURL="sendMessage?cid="+chatId+"&uid="+userId+"&msg="+document.getElementById('txt_message').value;
        //建立请求连接
        sendReq.open("POST",submitURL,true);
        sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        //当请求状态改变时调用handleSendChat()方法
        sendReq.onreadystatechange = handleSendChat();
        //发送请求
        sendReq.send(null);
        //设置提交消息文本框为空
        document.getElementById('txt_message').value='';
    }
}
//请求状态改变时调用handleSendChat()方法
function handleSendChat(){
    //取消间隔获取数据的方法
    clearInterval(mTimer);
    //从新获取调用getChatText()方法
    getChatText();
}